/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package orders

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/common"
	//"github.com/mjiulee/lego/utils"
)

/* 根据id获取记录
 * -----------------
 */
func (t *Orders) RecodeById(id int64) *Orders {
	item := new(Orders)
	_, err := lego.GetDBEngine().ID(id).Where("if_del = ?", 0).Get(item)
	if item.Id <= 0 || err != nil {
		return nil
	}
	return item
}

func (t *Orders) RecodeByWho(who *common.Who,id int64) *Orders {
	item := new(Orders)
	_, err := lego.GetDBEngine().ID(id).Where("if_del = ?", 0).And("uid = ?",who.Uid).Get(item)
	if item.Id <= 0 || err != nil {
		return nil
	}
	return item
}

/* 添加
 * -----------------
 */
func (t *Orders) AddRecode(item2add *Orders) bool {
	item2add.Id = lego.UUID()
	item2add.OrderCode = utils.Int64ToString(item2add.Id)
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *Orders) AddRecodeWithsession(session *xorm.Session, item2add *Orders) bool {
	item2add.Id = lego.UUID()
	item2add.OrderCode = utils.Int64ToString(item2add.Id)
	_, err := session.Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *Orders) DelRecodeById(id int64) bool {
	item := new(Orders)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *Orders) DelRecodeByIdWithSession(session *xorm.Session, id int64) bool {
	item := new(Orders)
	_, err := session.ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 更新
 * -----------------*/
func (t *Orders) UpdateRecode(rc *Orders) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Omit("id", "if_del").Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *Orders) UpdateRecodeWithSession(session *xorm.Session, rc *Orders) bool {
	_, err := session.ID(rc.Id).Omit("id", "if_del").Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/*查询表名, 注意，函数名不能定义未TableName()，因为会与xorm内部使用的TableName冲突*/
func (t *Orders) TName() string {
	tname := lego.GetDBEngine().TableName(t)
	return tname
}

func (t *Orders) ListOrdersByWho(who *common.Who, orderCode, userName, mobile, beginTime, endTime, productName string, orderType int, shopids []int64, page, psize int, orderField, order string, orderStatus int) ([]*OrderList, int64, error) {

	start := ((page-1) * psize)
	resultList := make([]*OrderList, 0)

	session := lego.GetDBEngine().Table("tb_orders").Alias("t1").

		Join("left", []string{"tb_e_shop", "t2"}, "t2.id = t1.e_shop_id").
		Where("t1.if_del = ?", 0).
		In("t2.id", shopids)

	switch orderStatus {
	case UnPayOrder:
		session = session.Where("t1.if_pay = ?", 0)
	case PayOrderWaitDelivery:
		session = session.Where("t1.if_pay = ?", 1).And("t1.if_delivery = ?", 0)
	case SendedOrder:
		session = session.Where("t1.if_delivery = ?", 1).And("t1.if_finish = ?", 0).Where("t1.if_cancel = ?", 0)
	case FinishOrder:
		session = session.Where("t1.if_finish = ?", 1)
	case CancelOrder:
		session = session.Where("t1.if_cancel = ?", 1)
	case RefundOrder:
		session = session.Where("t1.if_refund = ? or t1.if_refund = ?", Refunding, AgreeRefund)
	}

	if len(orderCode) > 0 {
		orderCode = "%" + orderCode + "%"
		session = session.Where("t1.order_code like ?", orderCode)
	}

	if len(userName) > 0 {
		userName = "%" + userName + "%"
		session = session.Where("t1.user_name like ?", userName)
	}

	if len(mobile) > 0 {
		mobile = "%" + mobile + "%"
		session = session.Where("t1.mobile like ?", mobile)
	}

	if len(beginTime) > 0 {
		session = session.Where("t1.cdate >= ?", beginTime)
	}

	if len(endTime) > 0 {
		session = session.Where("t1.cdate <= ?", endTime)
	}

	if len(productName) > 0 {
		productName = "%" + productName + "%"
		session = session.Where("exists (select 1 from tb_order_detail detail where detail.order_id = t1.id and detail.product_name like ?)", productName)
	}

	if orderType > 0 {
		session = session.Where("t1.order_type = ?", orderType)
	}

	if orderField != "" && order != "" {
		orderStr := fmt.Sprintf("t1.%s %s", orderField, order)
		session = session.OrderBy(orderStr)
	} else {
		session = session.OrderBy("t1.cdate desc")
	}

	session2 := session.Clone()

	//Desc("t1.cdate")
	//Asc()
	//OrderBy("asc")
	//Limit(psize, start).
	err := session.Limit(psize, start).Select("t1.*,t2.shop_name").Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err

}

type OrderList struct {
	Orders  `xorm:"extends"`
	ShopName string
}

func (t *Orders) ListOrdersByWhoForMall(who *common.Who, orderCode string, orderType int, shopid int64, page, psize int, orderField, order string, orderStatus int) ([]*Orders, int64, error) {

	start := ((page-1) * psize)
	resultList := make([]*Orders, 0)

	session := lego.GetDBEngine().Table("tb_orders").Alias("t1").
		//Select("t1.*").
		Where("t1.if_del = ?", 0).
		And("t1.e_shop_id = ?", shopid).
		And("t1.uid = ?", who.Uid)

	switch orderStatus {
	case UnPayOrder:
		session = session.Where("t1.if_pay = ?", 0)
	case PayOrderWaitDelivery:
		session = session.Where("t1.if_pay = ?", 1).And("t1.if_delivery = ?", 0)
	case SendedOrder:
		session = session.Where("t1.if_delivery = ?", 1).And("t1.if_finish = ?", 0).Where("t1.if_cancel = ?", 0)
	case FinishOrder:
		session = session.Where("t1.if_finish = ?", 1)
	case CancelOrder:
		session = session.Where("t1.if_cancel = ?", 1)
	case RefundOrder:
		session = session.Where("t1.if_refund = ? or t1.if_refund = ?", Refunding, AgreeRefund)
	}

	if len(orderCode) > 0 {
		orderCode = "%" + orderCode + "%"
		session = session.Where("t1.order_code like ?", orderCode)
	}

	if orderType > 0 {
		session = session.Where("t1.order_type = ?", orderType)
	}

	if orderField != "" && order != "" {
		orderStr := fmt.Sprintf("t1.%s %s", orderField, order)
		session = session.OrderBy(orderStr)
	} else {
		session = session.OrderBy("t1.cdate desc")
	}

	//Desc("t1.cdate")
	//Asc()
	//OrderBy("asc")

	session2 := session.Clone()

	//Desc("t1.cdate")
	//Asc()
	//OrderBy("asc")
	//Limit(psize, start).
	err := session.Limit(psize, start).Select("t1.*,t2.shop_name").Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err


	//session2 := *session.Clone()
	//session = session.
	//	Limit(psize, start)
	//err := session.Find(&resultList)
	//if err != nil {
	//	return nil, 0, err
	//}
	//
	//total, err := session2.Count()
	//if err != nil {
	//	return nil, 0, err
	//}
	//return resultList, total, err
}
